<template>
	<view>
		<view class="content">
			<u-swiper :list="bannerList" height="200" indicator indicatorMode="dot" indicatorInactiveColor="#8df"
				indicatorStyle="bottom: 10px;"></u-swiper>
			<view>
				<u-tabs :list="tablist" lineColor="#0bc5ae" :current="current" :activeStyle="{
                    fontWeight: 'bold',
                }" :scrollable="false" @click="click"></u-tabs>
			</view>
			<view v-for="(item, index) in itemList" :key="index">
				<view class="order-card" @click="onItemClick(item.serverId)">
					<view class="title-and-status">
						<view class="title-left">
							<view class="title-main">
								{{ item.serverValue }}
							</view>
							<!-- <view class="subhead">
                                  {{item.title}}
                              </view> -->
						</view>
						<view class="status-box">
							<view class="status">
								<span style="font-weight: normal"></span>
								<span class="status-price">￥{{ item.halfRrice }}</span>
							</view>
					<!-- 		<view class="status-line">
								<span style="font-weight: normal">￥</span>
								<span class="status-price">{{ item.allPrice }}</span>
							</view> -->
						</view>
					</view>
					<view class="item-tag" style="margin-bottom: 25rpx">
						<view class="service-tag" :key="idx" v-for="(service, idx) in item.categoryValueList">
							{{ service }}
						</view>
					</view>
				</view>
			</view>
			<!-- <view class="grid">
                  <view v-for="(gridItem, index1) in gridList" :key="index1">
                      <view class="catalogue-title">
                          {{ gridItem.title }}
                      </view>
                      <view class="grid-list">
                          <view
                              spacing="0"
                              margin="5px"
                              class="grid-item"
                              @click="onItemClick(gridItem.code, item.serverId)"
                              v-for="(item, index2) in gridItem.nurseServersList"
                              :key="index2"
                          >
                              <view class="grid-title">
                                  {{ item.serverValue }}
                              </view>
                              <view class="grid-introduce">
                                  {{ item.categoryValue }}
                              </view>
                          </view>
                      </view>
                  </view>
              </view> -->
		</view>
	</view>
</template>

<script>
	import {
		getNurseServe,adminOpenId
	} from "../../common/api/index.js"
	import { getToken } from "@/utils/auth.js"
	import { subscribeMessage } from "../../utils/index.js";
	export default {
		components: {},
		data() {
			return {
				token: getToken(),
				tabbarValue: 0,
				templateId: 'MM43WkRzz_BCBQti-dtKD4S3YlsNKyn9YP6fhicyeHs',
				openId:'ofuml6zQHd7CNukDGITkcdvVtApg',
				titles: ["护士上门", "消息", "订单"],
				gridList: [],
				tablist: [],
				current: 1,
				itemList: [],
			}
		},
		onLoad() {
		},
		mounted() {
			this.initServe()
		},
		methods: {
			
			onItemClick(serverId) {
				let that = this;
				if (!this.token) {
					uni.showToast({
						icon: 'none',
						title: '请重新登录!',
						delay: 1500
					})
					setTimeout(() => {
						uni.setStorageSync("nav_to_index_index", 1)
						uni.reLaunch({ url: "/pages/index/index" })
					}, 2000)
					return
				}
				
				let code = this.gridList[this.current].code
				if(code === "visit"){
					// uni.navigateTo({
					// 	url: `/nursingWorkerPages/pages/CompanionVisit/CompanionVisit?code=${code}&serverId=${serverId}`,
					// })
					uni.navigateTo({
						url: `/nursingWorkerPages/pages/CompanionVisit/visitDetil?code=${code}&serverId=${serverId}`,
					})
				}else{
					const values="护工上门"
					uni.navigateTo({
						url: `/nursingWorkerPages/pages/itemDetail/itemDetail?code=${code}&serverId=${serverId}&value=${values}`,
					})		
				}
			
			},
			initServe() {
				getNurseServe().then((res) => {
					console.log("res", res)
					let data = res.data.data
					this.gridList = data
					this.itemList = this.gridList[this.current].nurseServersList
					this.tablist = data.map((item, index) => {
						let disabled = false
						// if (index == 0) {
						// 	disabled = true
						// } else {
						// 	disabled = false
						// }
						return {
							name: item.title,
							disabled: disabled,
						}
					})
				})
			},
			click(item) {
				console.log("item", item)

				// if (item.index !== 0) {
				// 	this.current = item.index
				// 	this.itemList = this.gridList[this.current].nurseServersList
				// }
				this.current = item.index
				this.itemList = this.gridList[this.current].nurseServersList

			},
			// 前端页面/组件中
			
			    subscribeMsg(serverId) {
			    // 模板 ID 数组（可同时请求多个模板，但需用户逐一确认）
			    // const templateIds = ['ECBQnn0plovzljftmioB9-wdyBncXQwcru9AF0hVxSs','1p7Z_SSvpsYroEhNz9OKedmie1bnUwzkx3XvgYD2mDg']; 
			    // uni.requestSubscribeMessage({
			    //   tmplIds: templateIds,
			    //   success: (res) => {
			    //     // res 是对象，键为模板 ID，值为用户订阅结果：
			    //     // 'accept'（同意）、'reject'（拒绝）、'ban'（被封禁）
			    //     if (res['ECBQnn0plovzljftmioB9-wdyBncXQwcru9AF0hVxSs'] === 'accept') {
			    //       // 用户同意订阅，触发后端发送消息
			    //     } else {
			    //       uni.showToast({ title: '订阅失败，无法接收通知', icon: 'none' });
			    //     }
			    //   },
			    //   fail: (err) => {
			    //     console.error('订阅失败:', err);
			    //     uni.showToast({ title: '订阅失败，请重试', icon: 'none' });
			    //   }
			    // });
				// wx.login({
				// 		success: async res => {
				// 		  const code = res.code
				// 		  const res2 = await adminOpenId({
				// 			code,
				// 		  })
				// 		  // const openid = res2.data.data.openid
				// 		  this.openId = res2.data.data.openid
				// 		  uni.setStorageSync('openid', openid)
				// 		}
				// 	  })
				  this.sendMsgToServer(serverId);
			  },
			
			  // 调用后端接口发送消息
			  async  sendMsgToServer(serverId) {
				  let code = this.gridList[this.current].code
			    try {
			      const res = await uni.request({
			        // url: 'http://192.168.1.21:8050/applet/user/nurse/access/pushMessage',
				    url: 'http://192.168.1.21:8050/applet/user/nurse/access/adminMessage',
			        method: 'POST',
			        data: {
			          templateId: this.templateId,
					  type:'user',
			          openId: this.openId , // 用户 openid（需提前获取）
			          // page: `/nursingWorkerPages/pages/itemDetail/itemDetail?code=${code}&serverId=${serverId}` // 点击消息跳转的小程序页面（可选）
			          // data: { // 模板变量（需与模板定义的关键词匹配）
			          //   thing1: { value: '订单标题' },
			          //   date2: { value: '2025-08-15' },
			          //   thing3: { value: '物流状态：已发货' }
			          // }
			        }
			      });
				  console.log("item", res)
			      if (res.data.code === 0) {
			        uni.showToast({ title: '消息已发送' });
			      } else {
			        uni.showToast({ title: '发送失败', icon: 'none' });
			      }
			    } catch (error) {
			      console.error('请求后端失败:', error);
			    }
			  }
		},
	};
</script>

<style lang="scss" scoped>
	.grid {
		padding: 15rpx;
		margin: 15rpx 0;

		.catalogue-title {
			font-size: 30rpx;
			margin: 10rpx 0;
			height: 40rpx;
			line-height: 40rpx;
			font-weight: 700;
			padding-left: 25rpx;
			// background: url(../../static/icon_rect.png) left center no-repeat;
			background-size: 15rpx auto;
			margin-left: 10rpx;
		}
	}

	.grid-list {
		display: flex;
		justify-content: space-between;
		align-items: center;
		flex-wrap: wrap;
	}

	.grid .grid-list:first-child .grid-item:nth-child(1) {
		// background: url('/nursingWorkerPages/static/bg-1.png') center center no-repeat;
		background-size: 100% 100%;
	}

	.grid .grid-list:first-child .grid-item:nth-child(2) {
		// background: url('/nursingWorkerPages/static/bg-2.png') center center no-repeat;
		background-size: 100% 100%;
	}

	.grid .grid-list:first-child .grid-item:nth-child(3) {
		// background: url('/nursingWorkerPages/static/bg-3.png') center center no-repeat;
		background-size: 100% 100%;
	}

	.grid .grid-list:first-child .grid-item:nth-child(4) {
		// background: url('/nursingWorkerPages/static/bg-4.png') center center no-repeat;
		background-size: 100% 100%;
	}

	.grid .grid-list:nth-child(2) .grid-item:nth-child(1) {
		// background: url('/nursingWorkerPages/static/bg-5.png') center center no-repeat;
		background-size: 100% 100%;
	}

	.grid .grid-list:nth-child(2) .grid-item:nth-child(2) {
		// background: url('/nursingWorkerPages/static/bg-6.png') center center no-repeat;
		background-size: 100% 100%;
	}

	.grid .grid-list:nth-child(2) .grid-item:nth-child(3) {
		// background: url('/nursingWorkerPages/static/bg-7.png') center center no-repeat;
		background-size: 100% 100%;
	}

	.grid .grid-list:nth-child(2) .grid-item:nth-child(4) {
		// background: url('/nursingWorkerPages/static/bg-8.png') center center no-repeat;
		background-size: 100% 100%;
	}

	.grid .grid-list:nth-child(2) .grid-item:nth-child(5) {
		// background: url('/nursingWorkerPages/static/bg-9.png') center center no-repeat;
		background-size: 100% 100%;
	}

	.grid-item {
		width: 340rpx;
		margin: 5px;
		padding: 20rpx;
		box-shadow: 0px 0px 3px 1px rgba(0, 0, 0, 0.08);
		// background-size: 100% 100%;
		border-radius: 5rpx;

		.grid-title {
			color: #14141c;
			font-size: 26rpx;
			font-weight: 700;
			margin-bottom: 20rpx;
		}

		.grid-introduce {
			color: #a8b4b6;
			display: -webkit-box;
			display: -ms-flexbox;
			height: 40px;
			overflow: hidden;
			font-size: 25rpx;
			line-height: 20px;
		}
	}

	.order-card {
		margin-right: 30rpx;
		margin-left: 30rpx;
		background: white;
		padding: 30rpx;
		box-sizing: border-box;
		border-radius: 16rpx;
		margin-top: 20rpx;
		display: flex;
		flex-direction: column;

		.title-and-status {
			display: flex;
			width: 100%;
			justify-content: space-between;

			.title-left {
				display: flex;
				justify-content: flex-start;
				width: 65%;
				align-items: flex-end;

				.title-main {
					color: #333333;
					font-size: 35rpx;
					font-weight: 700;
					margin-right: 10rpx;
				}

				.subhead {
					color: #747474;
					font-size: 28rpx;
				}
			}

			.time {
				flex: 1;
				color: rgba(35, 35, 35, 0.7);
				font-size: 26rpx;
			}

			.status-box {
				display: flex;
				justify-content: center;
				align-items: center;

				.status {
					font-size: 35rpx;
					font-weight: 700;
					color: #333333;

					.status-price {
						color: #ffb35b;
					}
				}

				.status-line {
					font-size: 28rpx;
					font-weight: 700;
					color: #bdbdbd;
					text-decoration: line-through;
					margin-left: 10rpx;
					text-align: center;

					.status-price {
						color: #bdbdbd;
					}
				}
			}
		}

		.item-tag {
			display: flex;
			justify-content: flex-start;
			// width: 80%;
			align-items: center;
			margin-top: 20rpx;
			flex-wrap: wrap;
			min-height: 130rpx;

			.service-tag {
				min-width: 110rpx;
				background-color: #eafaf5;
				font-size: 20rpx;
				color: #6f7070;
				padding: 10rpx;
				height: 50rpx;
				line-height: 30rpx;
				text-align: center;
				border-radius: 25rpx;
				margin-right: 10rpx;
				margin-bottom: 10rpx;
			}
		}

		.cycle-and-price {
			display: flex;
			justify-content: space-between;
			font-size: 25rpx;
			color: #6c6c6c;
			margin-top: 10rpx;

			.cycle {
				width: 80%;
			}

			.price {}
		}

		.project-row {
			display: flex;
			align-items: center;
			margin-top: 36rpx;

			.img {
				width: 136rpx;
				height: 136rpx;
				border-radius: 20rpx;
			}

			.name {
				color: #232323;
				font-size: 32rpx;
				font-weight: bold;
				margin-left: 24rpx;
			}
		}

		.info-row {
			display: flex;
			margin-top: 40rpx;

			.name {
				width: 136rpx;
				color: rgba(35, 35, 35, 0.7);
				font-size: 26rpx;
			}

			.value {
				color: #232323;
				font-size: 26rpx;
			}
		}

		.div-line {
			width: 100%;
			height: 2rpx;
			background: #f8f8f8;
			margin-top: 40rpx;
		}

		.price-and-pay {
			display: flex;
			align-items: center;
			margin-top: 20rpx;

			.left {
				display: flex;
				align-items: center;
				flex: 1;
			}

			.cancel-btn {
				width: 150rpx;
				height: 60rpx;
				border: solid 2rpx rgba(35, 35, 35, 0.26);
				border-radius: 60rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				color: rgba(35, 35, 35, 0.8);
				font-size: 26rpx;
				margin-left: 8rpx;
				margin-right: 8rpx;
			}

			.ok-btn {
				width: 150rpx;
				height: 60rpx;
				border: solid 2rpx #0bc5ae;
				border-radius: 60rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				color: #0bc5ae;
				font-size: 26rpx;
				margin-left: 8rpx;
				margin-right: 8rpx;
			}
		}
	}
</style>